<template>
  <div>
    <DynamicTable
      row-key="id"
      header-title="用户管理"
      :data-request="Api.user.userPage"
      :columns="columns"
      bordered
      size="small"
    >
      <template #toolbar>
        <a-button type="primary" @click="openUserModal({})"> 新增 </a-button>
      </template>
    </DynamicTable>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import type { TableColumn } from '@/components/core/dynamic-table';
  import { useTable } from '@/components/core/dynamic-table';
  import { useFormModal } from '@/hooks/useModal/';
  import Api from '@/api/';
  import { formatToDateTime } from '@/utils/dateUtil';

  defineOptions({
    name: 'StudentUsers',
  });

  interface TableListItem {
    id: number;
    username: string;
    password: string;
    phone: string;
    createTime: string;
  }

  const [DynamicTable, dynamicTableInstance] = useTable({
    pagination: {
      pageSize: 10,
      showSizeChanger: true,
      showQuickJumper: true,
    },
  });
  const [showModal] = useFormModal();

  const classList = ref([]);

  onMounted(async () => {
    const data = await Api.student.classList({});
    classList.value = data;
  });

  const formSchemas = [
    {
      field: 'userName',
      label: '用户名',
      component: 'Input',
      required: true,
    },
    {
      field: 'loginName',
      label: '登录名',
      component: 'Input',
      required: true,
    },
    {
      field: 'loginPwd',
      label: '密码',
      component: 'InputPassword',
      required: true,
      show: (formModel) => !formModel.id,
    },
    {
      field: 'userType',
      label: '用户类型',
      component: 'Select',
      componentProps: {
        options: [
          { label: '学生', value: 1 },
          { label: '老师', value: 2 },
          { label: '管理员', value: 3 },
        ],
      },
      required: true,
    },
    {
      field: 'userStatus',
      label: '用户状态',
      component: 'Select',
      componentProps: {
        options: [
          { label: '禁用', value: 0 },
          { label: '正常', value: 1 },
        ],
      },
      required: true,
    },
    {
      field: 'classesId',
      label: '绑定班级',
      component: 'Select',
      componentProps: {
        options: classList,
        fieldNames: {
          label: 'className',
          value: 'id',
        },
      },
      required: false,
    },
  ];

  /**
   * @description 打开新增/编辑弹窗
   */
  const openUserModal = async (record: Partial<TableListItem>) => {
    const [formRef] = await showModal({
      modalProps: {
        title: `${record.id ? '编辑' : '新增'}用户`,
        width: '50%',
        onFinish: async (values) => {
          if (record.id) {
            await Api.user.update({ id: record.id, ...values });
          } else {
            await Api.user.create(values);
          }
          dynamicTableInstance?.reload();
        },
      },
      formProps: {
        labelWidth: 100,
        schemas: formSchemas,
      },
    });
    formRef?.setFieldsValue(record);
  };

  const delRowConfirm = async (record: TableListItem) => {
    await Api.user.delete({ id: record.id });
    dynamicTableInstance?.reload();
  };

  const columns: TableColumn<TableListItem>[] = [
    {
      title: '用户ID',
      dataIndex: 'id',
      width: 80,
      hideInSearch: true,
    },
    {
      title: '用户名',
      dataIndex: 'userName',
    },
    {
      title: '登录名',
      dataIndex: 'loginName',
    },
    {
      title: '用户类型',
      dataIndex: 'userType',
      customRender: ({ text }) => {
        const typeMap = {
          1: '学生',
          2: '老师',
          3: '管理员',
        };
        return typeMap[text] || text;
      },
      formItemProps: {
        component: 'Select',
        componentProps: {
          options: [
            { label: '学生', value: 1 },
            { label: '老师', value: 2 },
            { label: '管理员', value: 3 },
          ],
        },
      },
    },
    {
      title: '用户状态',
      dataIndex: 'userStatus',
      customRender: ({ text }) => {
        const statusMap = {
          0: '禁用',
          1: '正常',
        };
        return statusMap[text] || text;
      },
      formItemProps: {
        component: 'Select',
        componentProps: {
          options: [
            { label: '禁用', value: 0 },
            { label: '正常', value: 1 },
          ],
        },
      },
    },
    {
      title: '绑定班级',
      dataIndex: 'classesId',
      customRender: ({ text }) => {
        const classItem = classList.value.find((item) => item.id === text);
        return classItem?.className || text;
      },
      formItemProps: {
        component: 'Select',
        componentProps: {
          options: classList,
          fieldNames: {
            label: 'className',
            value: 'id',
          },
        },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 180,
      hideInSearch: true,
      customRender: ({ text }) => formatToDateTime(text),
    },
    {
      title: '操作',
      width: 130,
      dataIndex: 'ACTION',
      hideInSearch: true,
      fixed: 'right',
      actions: ({ record }) => [
        {
          label: '编辑',
          onClick: () => openUserModal(record),
        },
        // {
        //   label: '删除',
        //   popConfirm: {
        //     title: '你确定要删除吗？',
        //     placement: 'left',
        //     onConfirm: () => delRowConfirm(record),
        //   },
        // },
      ],
    },
  ];
</script>
